<!--
  智慧社区管理系统 - 个人中心
  @author Wu.Liang
  @date 2024-01-01
  @updated 2025-01-30 - 完善个人中心页面设计，移除权限展示，优化用户体验
-->
<template>
  <div class="profile-container">
    <!-- 主要内容区域 -->
    <div class="profile-content">
      <!-- 左侧：用户信息卡片 -->
      <div class="profile-left">
        <el-card class="user-info-card" shadow="hover">
          <div class="user-avatar-section">
            <el-avatar :size="120" class="user-avatar">
              {{ getUserInitial() }}
            </el-avatar>
            <div class="user-status">
              <el-tag :type="userDetail?.status === 1 ? 'success' : 'danger'" size="small">
                {{ userDetail?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </div>
          </div>
          
          <div class="user-basic-info">
            <h3 class="user-name">{{ getUserDisplayName() }}</h3>
            <p class="user-username">@{{ userDetail?.username }}</p>
          </div>

          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-number">{{ formatDate(userDetail?.createTime) }}</div>
              <div class="stat-label">注册时间</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ userDetail?.lastLoginTime ? formatDate(userDetail.lastLoginTime) : '暂无' }}</div>
              <div class="stat-label">最后登录</div>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作卡片 -->
        <el-card class="quick-actions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Operation /></el-icon>
              <span>快捷操作</span>
            </div>
          </template>
          
          <div class="quick-actions">
            <el-button type="primary" @click="handleEditProfile" class="action-btn">
              <el-icon><Edit /></el-icon>
              编辑资料
            </el-button>
            <el-button @click="handleChangePassword" class="action-btn">
              <el-icon><Lock /></el-icon>
              修改密码
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 右侧：详细信息 -->
      <div class="profile-right">
        <!-- 基本信息 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><UserFilled /></el-icon>
              <span>基本信息</span>
              <el-button text @click="handleEditProfile" class="edit-btn">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名">
              {{ userDetail?.username || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="真实姓名">
              {{ userDetail?.realName || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="昵称">
              {{ userDetail?.nickname || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号码">
              {{ userDetail?.phone || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱地址" :span="2">
              {{ userDetail?.email || '未设置邮箱' }}
            </el-descriptions-item>
            <el-descriptions-item label="用户类型">
              {{ getUserTypeName() }}
            </el-descriptions-item>
            <el-descriptions-item label="账户状态">
              <el-tag :type="userDetail?.status === 1 ? 'success' : 'danger'">
                {{ userDetail?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="最后登录时间" :span="2">
              {{ userDetail?.lastLoginTime ? formatDateTime(userDetail.lastLoginTime) : '暂无登录记录' }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录IP" :span="2">
              {{ userDetail?.lastLoginIp || '未知' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 安全设置 -->
        <el-card class="info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </div>
          </template>
          
          <div class="security-items">
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录密码</div>
                <div class="security-desc">定期更换密码可提高账户安全性</div>
              </div>
              <el-button @click="handleChangePassword" type="primary" size="small">
                修改
              </el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">手机验证</div>
                <div class="security-desc">
                  {{ userDetail?.phone ? '已绑定手机：' + maskPhone(userDetail.phone) : '未绑定手机号码' }}
                </div>
              </div>
              <el-button @click="handleBindPhone" :type="userDetail?.phone ? 'default' : 'primary'" size="small">
                {{ userDetail?.phone ? '更换' : '绑定' }}
              </el-button>
            </div>
            
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">邮箱验证</div>
                <div class="security-desc">
                  {{ userDetail?.email ? '已绑定邮箱：' + maskEmail(userDetail.email) : '未绑定邮箱地址' }}
                </div>
              </div>
              <el-button @click="handleBindEmail" :type="userDetail?.email ? 'default' : 'primary'" size="small">
                {{ userDetail?.email ? '更换' : '绑定' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑个人资料" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        :rules="editRules" 
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱地址" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProfile" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage, type FormInstance } from 'element-plus'
import { 
  User, 
  UserFilled, 
  Edit, 
  Lock, 
  Operation
} from '@element-plus/icons-vue'
import { updateCurrentUserProfile, getUserById } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const editDialogVisible = ref(false)
const saving = ref(false)
const editFormRef = ref<FormInstance>()
const userDetail = ref<any>(null)
const loading = ref(false)

// 编辑表单数据
const editForm = reactive({
  username: undefined as string | undefined,
  realName: undefined as string | undefined,
  nickname: undefined as string | undefined,
  phone: undefined as string | undefined,
  email: undefined as string | undefined
})

// 表单验证规则
const editRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        // 如果是脱敏数据（包含*号），则跳过格式校验
        if (value.includes('*')) {
          callback()
          return
        }
        // 否则进行格式校验
        const pattern = /^1[3-9]\d{9}$/
        if (!pattern.test(value)) {
          callback(new Error('请输入正确的手机号码'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  email: [
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        // 如果是脱敏数据（包含*号），则跳过格式校验
        if (value.includes('*')) {
          callback()
          return
        }
        // 否则进行格式校验
        const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailPattern.test(value)) {
          callback(new Error('请输入正确的邮箱地址'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ]
}

// 计算属性
const getUserInitial = () => {
  const name = userDetail.value?.realName || userDetail.value?.username || 'U'
  return name.charAt(0).toUpperCase()
}

const getUserDisplayName = () => {
  return userDetail.value?.realName || userDetail.value?.username || '未知用户'
}

const getUserTypeName = () => {
  const userType = userDetail.value?.userType
  const typeMap: Record<string, string> = {
    'SUPER_ADMIN': '超级管理员',
    'PROPERTY_ADMIN': '物业管理员',
    'COMMUNITY_ADMIN': '社区管理员',
    'BUILDING_ADMIN': '楼栋管理员',
    'UNIT_ADMIN': '单元管理员',
    'HOUSEHOLD_ADMIN': '房户管理员',
    'NORMAL_USER': '普通用户'
  }
  return typeMap[userType] || '普通用户'
}

// 工具方法
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '未知'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

const formatDateTime = (dateStr?: string) => {
  if (!dateStr) return '未知'
  return new Date(dateStr).toLocaleString('zh-CN')
}

const maskPhone = (phone: string) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

const maskEmail = (email: string) => {
  const [username, domain] = email.split('@')
  const maskedUsername = username && username.length > 2 
    ? username.substring(0, 2) + '*'.repeat(username.length - 2)
    : username || ''
  return `${maskedUsername}@${domain}`
}

// 获取用户详情
const fetchUserDetail = async () => {
  try {
    loading.value = true
    const userId = userStore.userInfo?.id
    if (!userId) {
      ElMessage.error('用户信息获取失败')
      return
    }
    
    // 并行获取用户详情和角色信息
    const userResponse = await getUserById(userId)
    
    if (userResponse.data) {
      userDetail.value = userResponse.data
    }
  } catch (error: any) {
    ElMessage.error('获取用户详情失败：' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 事件处理方法
const handleEditProfile = () => {
  // 初始化编辑表单
  editForm.username = userDetail.value?.username || undefined
  editForm.realName = userDetail.value?.realName || undefined
  editForm.nickname = userDetail.value?.nickname || undefined
  editForm.phone = userDetail.value?.phone || undefined
  editForm.email = userDetail.value?.email || undefined
  editDialogVisible.value = true
}

const handleSaveProfile = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    saving.value = true
    
    // 处理提交数据，过滤掉脱敏字段
    const submitData: any = {}
    
    if (editForm.realName && !editForm.realName.includes('*')) {
      submitData.realName = editForm.realName
    }
    // 昵称字段：允许空字符串，但过滤脱敏数据
    if (editForm.nickname !== undefined && !editForm.nickname.includes('*')) {
      submitData.nickname = editForm.nickname
    }
    if (editForm.phone && !editForm.phone.includes('*')) {
      submitData.phone = editForm.phone
    }
    if (editForm.email && !editForm.email.includes('*')) {
      submitData.email = editForm.email
    }
    
    const response = await updateCurrentUserProfile(submitData)
    
    if (response.data) {
      // 更新用户信息
      userStore.updateUserInfo(response.data)
      // 重新获取用户详情
      await fetchUserDetail()
      ElMessage.success('个人资料更新成功')
      editDialogVisible.value = false
    }
  } catch (error: any) {
    ElMessage.error('更新失败：' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

const handleChangePassword = () => {
  router.push('/profile/change-password')
}

const handleBindPhone = () => {
  ElMessage.info('手机绑定功能开发中...')
}

const handleBindEmail = () => {
  ElMessage.info('邮箱绑定功能开发中...')
}

// 监听对话框显示状态，确保每次打开时清除验证错误
watch(
  () => editDialogVisible.value,
  (visible) => {
    if (visible) {
      nextTick(() => {
        editFormRef.value?.clearValidate()
      })
    }
  }
)

// 生命周期
onMounted(() => {
  // 获取用户详情
  fetchUserDetail()
})
</script>

<style scoped lang="scss">
.profile-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.profile-content {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 24px;
  
  @media (max-width: 1200px) {
    grid-template-columns: 1fr;
  }
}

.profile-left {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.user-info-card {
  .user-avatar-section {
    text-align: center;
    margin-bottom: 20px;
    position: relative;
    
    .user-avatar {
      border: 4px solid #fff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    .user-status {
      position: absolute;
      bottom: 0;
      right: 50%;
      transform: translateX(50%);
    }
  }
  
  .user-basic-info {
    text-align: center;
    margin-bottom: 20px;
    
    .user-name {
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 4px 0;
    }
    
    .user-username {
      color: #909399;
      font-size: 14px;
      margin: 0;
    }
  }
  
  .user-stats {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    
    .stat-item {
      text-align: center;
      padding: 12px;
      background-color: #f8f9fa;
      border-radius: 8px;
      
      .stat-number {
        font-size: 14px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.quick-actions-card {
  .quick-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    
    .action-btn {
      justify-content: flex-start;
      height: 40px;
    }
  }
}

.profile-right {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-card {
  .card-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    
    .edit-btn {
      margin-left: auto;
    }
  }
}

.security-items {
  .security-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 0;
    border-bottom: 1px solid #ebeef5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .security-info {
      flex: 1;
      
      .security-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .security-desc {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}
</style>
